<template>
  <div class="workorder-edit-container">
    <div class="header-section">
      <div class="title-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workorder' }">工单列表</el-breadcrumb-item>
          <el-breadcrumb-item>编辑工单</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 class="page-title">编辑工单</h1>
      </div>
      <div class="action-buttons">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
      </div>
    </div>

    <div class="content-section" v-loading="pageLoading">
      <el-card class="form-card">
        <el-form 
          ref="formRef" 
          :model="workOrderForm" 
          :rules="rules"
          label-width="120px"
          label-position="top"
        >
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="工单编号">
                <el-input v-model="workOrderForm.orderNo" disabled />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="工单标题" prop="title">
                <el-input v-model="workOrderForm.title" placeholder="请输入工单标题" />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="工单类型" prop="typeId">
                <el-select 
                  v-model="workOrderForm.typeId" 
                  placeholder="请选择工单类型" 
                  class="full-width"
                >
                  <el-option 
                    v-for="item in typeOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="工单状态" prop="statusId">
                <el-select 
                  v-model="workOrderForm.statusId" 
                  placeholder="请选择工单状态" 
                  class="full-width"
                >
                  <el-option 
                    v-for="item in statusOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select 
                  v-model="workOrderForm.priority" 
                  placeholder="请选择优先级"
                  class="full-width"
                >
                  <el-option :value="1" label="低" />
                  <el-option :value="2" label="中" />
                  <el-option :value="3" label="高" />
                  <el-option :value="4" label="紧急" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="期望完成时间" prop="expectedFinishTime">
                <el-date-picker
                  v-model="workOrderForm.expectedFinishTime"
                  type="datetime"
                  placeholder="请选择期望完成时间"
                  class="full-width"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="负责部门" prop="departmentId">
                <el-select 
                  v-model="workOrderForm.departmentId" 
                  placeholder="请选择负责部门"
                  class="full-width"
                >
                  <el-option 
                    v-for="item in departmentOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="处理人" prop="handlerId">
                <el-select 
                  v-model="workOrderForm.handlerId" 
                  placeholder="请选择处理人"
                  class="full-width"
                  filterable
                >
                  <el-option 
                    v-for="item in handlerOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="工单内容" prop="content">
                <el-input 
                  v-model="workOrderForm.content" 
                  type="textarea" 
                  :rows="10" 
                  placeholder="请详细描述问题或需求"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { workOrder as workOrderApi } from '@/api'

export default {
  name: 'WorkOrderEdit',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref(null)
    const loading = ref(false)
    const pageLoading = ref(false)
    
    // 表单数据
    const workOrderForm = reactive({
      id: null,
      orderNo: '',
      title: '',
      typeId: null,
      statusId: null,
      priority: 2,
      departmentId: null,
      handlerId: null,
      handlerName: '',
      expectedFinishTime: null,
      content: ''
    })
    
    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入工单标题', trigger: 'blur' },
        { min: 5, max: 100, message: '标题长度在5-100个字符之间', trigger: 'blur' }
      ],
      typeId: [
        { required: true, message: '请选择工单类型', trigger: 'change' }
      ],
      statusId: [
        { required: true, message: '请选择工单状态', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入工单内容', trigger: 'blur' },
        { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
      ]
    }
    
    // 选项数据
    const typeOptions = ref([])
    const statusOptions = ref([])
    const departmentOptions = ref([])
    const handlerOptions = ref([])
    
    // 获取工单详情
    const getWorkOrderDetail = async (id) => {
      pageLoading.value = true
      try {
        const res = await workOrderApi.getWorkOrderDetail(id)
        if (res.data && res.data.code === 200) {
          const workOrder = res.data.data
          Object.keys(workOrderForm).forEach(key => {
            if (workOrder[key] !== undefined) {
              workOrderForm[key] = workOrder[key]
            }
          })
          
          // 日期类型特殊处理
          if (workOrderForm.expectedFinishTime) {
            workOrderForm.expectedFinishTime = new Date(workOrderForm.expectedFinishTime)
          }
        } else {
          ElMessage.error(res.data?.message || '获取工单详情失败')
        }
      } catch (error) {
        console.error('获取工单详情失败', error)
        ElMessage.error('获取工单详情失败')
      } finally {
        pageLoading.value = false
      }
    }
    
    // 获取工单类型选项
    const getTypeOptions = async () => {
      try {
        const res = await workOrderApi.getWorkOrderTypes()
        if (res.data && res.data.code === 200) {
          typeOptions.value = res.data.data || []
        }
      } catch (error) {
        console.error('获取工单类型失败', error)
        ElMessage.error('获取工单类型失败')
      }
    }
    
    // 获取工单状态选项
    const getStatusOptions = async () => {
      try {
        const res = await workOrderApi.getWorkOrderStatuses()
        if (res.data && res.data.code === 200) {
          statusOptions.value = res.data.data || []
        }
      } catch (error) {
        console.error('获取工单状态列表失败', error)
        ElMessage.error('获取工单状态列表失败')
      }
    }
    
    // 获取部门选项
    const getDepartmentOptions = () => {
      // TODO: 实现部门选项获取
      departmentOptions.value = [
        { id: 1, name: '客服部' },
        { id: 2, name: '技术支持部' },
        { id: 3, name: '硬件支持部' },
        { id: 4, name: '软件开发部' }
      ]
    }
    
    // 获取处理人选项
    const getHandlerOptions = () => {
      // TODO: 实现处理人选项获取
      handlerOptions.value = [
        { id: 101, name: '张三' },
        { id: 102, name: '李四' },
        { id: 103, name: '王五' },
        { id: 104, name: '赵六' }
      ]
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const res = await workOrderApi.updateWorkOrder(workOrderForm)
            if (res.data && res.data.code === 200) {
              ElMessage.success('更新工单成功')
              router.push(`/workorder/${workOrderForm.id}`)
            } else {
              ElMessage.error(res.data?.message || '更新工单失败')
            }
          } catch (error) {
            console.error('更新工单失败', error)
            ElMessage.error('更新工单失败')
          } finally {
            loading.value = false
          }
        } else {
          return false
        }
      })
    }
    
    // 返回列表页
    const goBack = () => {
      router.push(`/workorder/${route.params.id}`)
    }
    
    onMounted(() => {
      const id = route.params.id
      if (id) {
        getWorkOrderDetail(id)
      } else {
        router.push('/workorder')
      }
      
      getTypeOptions()
      getStatusOptions()
      getDepartmentOptions()
      getHandlerOptions()
    })
    
    return {
      formRef,
      workOrderForm,
      rules,
      loading,
      pageLoading,
      typeOptions,
      statusOptions,
      departmentOptions,
      handlerOptions,
      submitForm,
      goBack
    }
  }
}
</script>

<style scoped>
.workorder-edit-container {
  padding: 24px;
  background-color: #f9fafb;
  min-height: calc(100vh - 60px);
}

/* 标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 32px;
  font-weight: 300;
  color: #262626;
  margin: 8px 0 0;
  letter-spacing: -0.5px;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

/* 表单样式 */
.full-width {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-form--label-top .el-form-item__label) {
  margin-bottom: 4px;
  padding-bottom: 0;
}

:deep(.el-input__inner) {
  height: 40px;
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

/* 加载状态 */
.el-loading-mask {
  backdrop-filter: blur(3px);
  background-color: rgba(255, 255, 255, 0.7);
}
</style> 
 